const Koa = require('koa')
const app = new Koa()
const router = require('./routes')
const views = require('koa-views')
const serve = require('koa-static')
const u = require('./api')

// 挂载静态页面并载入ejs
app.use(views(__dirname + '/views', {
  map: {
    html: 'ejs'
  }
}))

// 访问静态资源
app.use(serve(__dirname + '/public'))

// 中间件
app.use(async (ctx, next) => {
  ctx.config = {
    tdk: {
      title: '彧胜实业',
      description: '彧胜实业',
      keywords: '彧胜实业'
    },
    banner: {
      bannerUrl: '',
      bannerTitle: '',
      bannerDesc: ''
    },
    ip: ctx.header['x-real-ip']
  }
  // 获取基本信息
  let getInfo = await u.getInfoFn()
  ctx.config.info = {
    companyName: getInfo.data.companyName || '',
    address: getInfo.data.address || '',
    telephone: getInfo.data.telephone || '',
    phone: getInfo.data.phone || '',
    qq: getInfo.data.qq || '',
    logo: getInfo.data.logo || '',
    qrCode: getInfo.data.qrCode || ''
  }
  // 获取导航
  let getNav = await u.getNavFn()
  ctx.config.nav = getNav.code == 200 ? getNav.data.list : []
  ctx.config.nav.forEach(item => {
    if (item.dhRoute == ctx.url) {
      // TDK
      ctx.config.tdk = {
        title: item.seoTitle,
        description: item.seoDescription,
        keywords: item.seoKeywords
      }
      // BANNER
      ctx.config.banner = {
        bannerUrl: item.bannerUrl,
        bannerTitle: item.bannerTitle,
        bannerDesc: item.bannerDesc
      }
    }
  })
  // 友情链接
  let getLink = await u.getLinkFn()
  ctx.config.link = getLink.code == 200 ? getLink.data.list : []
  // 新闻资讯类型
  let getNewsType = await u.getNewsTypeFn()
  ctx.config.navChildren = getNewsType.code == 200 ? getNewsType.data.list : []
  // 常见问题
  let pathArr = ctx.config.nav.filter(x=>x.dhRoute==ctx.url)
  if (pathArr.length > 0) {
    let getProblem = await u.getProblemFn(ctx.url)
    if (getProblem.code == 200 && getProblem.data) {
      getProblem.data.hotspotQaList.filter(x=>x.addTimeNow=u.formatDate(x.addTime, 'dd-mm'))
      getProblem.data.newestQaList.filter(x=>x.addTimeNow=u.formatDate(x.addTime, 'dd-mm'))
      getProblem.data.recommendQaList.filter(x=>x.addTimeNow=u.formatDate(x.addTime, 'dd-mm'))
      ctx.config.problem = getProblem.data
    }
  }
  // 首页常见问题
  if (ctx.url == '/') {
    let getProblem = await u.getProblemFn('/gszc.html')
    if (getProblem.code == 200 && getProblem.data) {
      getProblem.data.hotspotQaList.filter(x=>x.addTimeNow=u.formatDate(x.addTime, 'dd-mm'))
      getProblem.data.newestQaList.filter(x=>x.addTimeNow=u.formatDate(x.addTime, 'dd-mm'))
      getProblem.data.recommendQaList.filter(x=>x.addTimeNow=u.formatDate(x.addTime, 'dd-mm'))
      ctx.config.problem = getProblem.data
    }
  }

  await next()
})

// 挂载路由
app.use(router.routes()).use(router.allowedMethods())

// 配置服务
app.listen(3002, () => {
  console.log('server is running http://localhost:3002')
})